package com.ruoyi.thread;

import java.util.ArrayList;
import java.util.List;

/*在 Java 的 Thread 类中，join() 方法是用来等待当前线程结束执行的方法。当一个线程调用了另一个线程的 join() 方法时，调用线程会暂停执行，并等待被调用线程执行完毕后再继续执行。*/
public class Test {
    private static int number = 0;
    private static Object obj = new Object();

    /*Synchronized保证原子性
     */
    public static void main(String[] args) throws InterruptedException {
        testJoin();
        Runnable increment = () -> {
            for (int i = 0; i < 1000; i++) {
                synchronized (obj){
                    number++;
                }
//                number++;
            }
        };


        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(increment);
            t.start();
            list.add(t);
        }

        for (Thread t : list) {
            t.join();
        }

        System.out.println("number = " + number);
    }

    public static void testJoin() {
        Thread t = new Thread(() -> {
            try {
                System.out.println("Child thread is starting.");
                Thread.sleep(3000);
                System.out.println("Child thread is ending.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start(); // 启动子线程
        try {
            System.out.println("Main thread is waiting for child thread to finish.");
            t.join(); // 主线程等待子线程结束
            System.out.println("Main thread continues after child thread finishes.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
